import os
import sys
import signal
import subprocess
from time import sleep

# -------------------------- 配置项（仅需修改这部分！）--------------------------
# 1. 你的 Consul 可执行文件路径（替换为你本地的 consul.exe 路径）
CONSUL_PATH = r"D:\tools\consul\consul.exe"  # Windows 示例
# CONSUL_PATH = "/usr/local/bin/consul"  # Linux/Mac 示例

# 2. 各服务的目录（相对于项目根目录，不用改）
SERVICE_DIRS = {
    "user": "user-service",
    "friend": "friend-service",
    "gateway": "gateway-service"
}

# 3. 各服务的启动命令（不用改，和之前的手动启动命令一致）
START_COMMANDS = {
    "consul": [CONSUL_PATH, "agent", "-dev", "-client=0.0.0.0"],
    "user": ["poetry", "run", "start"],
    "friend": ["poetry", "run", "start"],
    "gateway": ["poetry", "run", "start"]
}

# -------------------------- 核心逻辑（不用改）--------------------------
# 存储所有子进程（用于后续关闭）
child_processes = []

def start_service(name: str, command: list, cwd: str = None):
    """启动单个服务，并记录进程"""
    print(f"\n[INFO] 开始启动 {name} 服务...")
    # 启动子进程，重定向输出到终端
    process = subprocess.Popen(
        command,
        cwd=cwd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
        bufsize=1  # 实时输出日志
    )
    # 记录进程
    child_processes.append((name, process))
    # 实时打印服务日志
    def print_logs(proc, service_name):
        while True:
            line = proc.stdout.readline()
            if not line:
                break
            print(f"[{service_name.upper()}] {line.strip()}")
    
    # 用子线程打印日志（不阻塞主进程）
    import threading
    threading.Thread(target=print_logs, args=(process, name), daemon=True).start()
    return process

def stop_all_services(signal_num=None, frame=None):
    """停止所有服务（捕获 Ctrl+C 时触发）"""
    print("\n\n[INFO] 开始停止所有服务...")
    for name, process in child_processes:
        if process.poll() is None:  # 进程还在运行
            print(f"[INFO] 停止 {name} 服务...")
            # 发送终止信号（Windows 用 Terminate，Linux/Mac 用 SIGTERM）
            if sys.platform == "win32":
                process.terminate()
            else:
                os.kill(process.pid, signal.SIGTERM)
            # 等待进程退出
            process.wait(timeout=5)
            print(f"[INFO] {name} 服务已停止")
    print("\n[INFO] 所有服务已停止，再见！")
    sys.exit(0)

def main():
    try:
        # 1. 先启动 Consul（必须第一个启动）
        consul_proc = start_service("consul", START_COMMANDS["consul"])
        # 等待 3 秒，确保 Consul 启动完成（避免服务注册失败）
        sleep(3)
        # 检查 Consul 是否启动成功
        if consul_proc.poll() is not None:
            print("[ERROR] Consul 启动失败！请检查 CONSUL_PATH 是否正确")
            sys.exit(1)

        # 2. 启动 user-service
        user_cwd = os.path.join(os.getcwd(), SERVICE_DIRS["user"])
        start_service("user", START_COMMANDS["user"], cwd=user_cwd)
        sleep(2)  # 等待 2 秒，避免服务间注册冲突

        # 3. 启动 friend-service
        friend_cwd = os.path.join(os.getcwd(), SERVICE_DIRS["friend"])
        start_service("friend", START_COMMANDS["friend"], cwd=friend_cwd)
        sleep(2)

        # 4. 启动 gateway-service（最后启动）
        gateway_cwd = os.path.join(os.getcwd(), SERVICE_DIRS["gateway"])
        start_service("gateway", START_COMMANDS["gateway"], cwd=gateway_cwd)

        # 5. 保持主进程运行，等待 Ctrl+C 停止
        print("\n[INFO] 所有服务启动完成！按 Ctrl+C 停止所有服务")
        while True:
            sleep(1)

    except KeyboardInterrupt:
        # 捕获 Ctrl+C，停止所有服务
        stop_all_services()
    except Exception as e:
        print(f"[ERROR] 启动服务时出错：{str(e)}")
        stop_all_services()

if __name__ == "__main__":
    main()